<template>
    <div class="generation-view">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>图文生成</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="tabs">
            <el-radio-group v-model="generationType" @change="setGenerationType">
                <el-radio-button :value="0">文案生成</el-radio-button>
                <el-radio-button :value="1">图片生成</el-radio-button>
                <el-radio-button :value="2">文案优化</el-radio-button>
            </el-radio-group>
        </div>

        <div class="content-wrapper">
            <div class="input-panel">
                <div class="form-container">
                    <el-form label-position="top">
                        <el-form-item label="关键词">
                            <div class="prompt-generator">
                                <el-input v-model="promptKeywords" placeholder="请输入AI绘画关键词" class="keywords-input"
                                    :disabled="isGenerating" clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="图像风格">
                            <el-select v-model="selectedStyle" placeholder="请选择一个图像风格" class="style-select"
                                :disabled="isGenerating" clearable>
                                <el-option v-for="style in imageStyles" :key="style.value" :label="style.label"
                                    :value="style.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item>
                            <el-button @click="generatePrompt" class="generate-btn"
                                :disabled="!promptKeywords || isGenerating" :loading="isGeneratingPrompt">
                                生成提示词
                            </el-button>
                        </el-form-item>

                        <el-form-item label="图片主题">
                            <el-input v-model="contentTheme" placeholder="请输入您要生成的图片主题" type="textarea"
                                :autosize="{ minRows: 8 }" resize="none" class="theme-input tall-textarea" clearable
                                :disabled="isGenerating" />
                        </el-form-item>
                    </el-form>

                    <div class="action-buttons">
                        <el-button type="primary" @click="startCreation" class="primary-button" :loading="isGenerating">
                            开始创作
                        </el-button>
                        <el-button @click="clearContent" :disabled="isGenerating">
                            清空内容
                        </el-button>
                    </div>
                </div>
            </div>

            <div class="divider"></div>

            <div class="output-panel">
                <div class="output-header">
                    <el-button style="color: #333" @click="clearGeneratedImage"
                        :disabled="!generatedImage || isGenerating">
                        <el-icon>
                            <Plus />
                        </el-icon> 新建
                    </el-button>
                    <el-button type="primary" @click="exportImage" :disabled="!generatedImage || isGenerating">
                        导出图片
                    </el-button>
                </div>

                <div class="output-content">
                    <template v-if="!generatedImage">
                        <el-empty :description="isGenerating ? '正在生成图片，请稍候...' : `填写左侧内容并点击'开始创作'生成图片`">
                            <template v-if="isGenerating" #image>
                                <el-icon class="is-loading" style="font-size: 40px; color: #409EFF;">
                                    <el-icon-loading />
                                </el-icon>
                            </template>
                        </el-empty>
                    </template>
                    <div v-else class="image-preview">
                        <el-image :src="generatedImage" fit="contain" style="width: 100%; height: 100%;"
                            :preview-src-list="[generatedImage]" :initial-index="0" :zoom-rate="1.2" :max-scale="7"
                            :min-scale="0.2" preview-teleported hide-on-click-modal />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Loading as ElIconLoading } from '@element-plus/icons-vue'
import { useSidebarStore } from '../../../stores/sidebar'
import { ElMessage } from 'element-plus'

const isElectron = typeof window !== 'undefined' && window.process && window.process.versions && window.process.versions.electron

let ipcRenderer, fs, path
if (isElectron) {
    ipcRenderer = window.require('electron').ipcRenderer
    fs = window.require('fs')
    path = window.require('path')
}

const router = useRouter()
const sidebarStore = useSidebarStore()
const generationType = computed(() => sidebarStore.generationType)

watch(() => sidebarStore.generationType, (newVal) => {
    const paths = ['/media/text-gen', '/media/image-gen', '/media/copy-opt']
    router.push(paths[newVal])
})

const setGenerationType = (type) => {
    sidebarStore.setGenerationType(type)
}

const imageStyles = ref([
    { value: 'realistic', label: '写实风格' },
    { value: 'anime', label: '动漫风格' },
    { value: 'watercolor', label: '水彩风格' },
    { value: 'oil_painting', label: '油画风格' },
    { value: 'pixel_art', label: '像素艺术' },
    { value: 'cyberpunk', label: '赛博朋克' },
    { value: 'minimalist', label: '极简主义' },
    { value: 'surrealism', label: '超现实主义' }
])

const selectedStyle = ref('')
const promptKeywords = ref('')
const isGeneratingPrompt = ref(false)
const contentTheme = ref('')
const generatedImage = ref(null)
const isGenerating = ref(false)

const generatePrompt = async () => {
    if (!promptKeywords.value.trim()) {
        ElMessage.warning('请输入关键词')
        return
    }

    contentTheme.value = ''
    isGeneratingPrompt.value = true

    try {
        const response = await fetch('https://api.coze.cn/open_api/v2/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer pat_ZUl4RCBk8d1jIfgXenubgBmJiZtGetsqoWC7rhS2vzusZqsooOxut3r5kCQ9kHsl',
            },
            body: JSON.stringify({
                bot_id: '7520506481084071976',
                user: '123456',
                query: `根据以下关键词生成AI绘画提示词，要求包含详细描述和风格信息。关键词：${promptKeywords.value}${selectedStyle.value ? '，风格：' + imageStyles.value.find(s => s.value === selectedStyle.value).label : ''}`,
                variables: {
                    text: `根据以下关键词生成AI绘画提示词，要求包含详细描述和风格信息。关键词：${promptKeywords.value}${selectedStyle.value ? '，风格：' + imageStyles.value.find(s => s.value === selectedStyle.value).label : ''}`,
                    prompt: promptKeywords.value
                },
                stream: false,
            }),
        })

        if (!response.ok) {
            throw new Error('提示词生成请求失败,状态码：' + response.status)
        }

        const data = await response.json()

        if (data.code !== 0 || !data.messages) {
            throw new Error(data.msg || 'API返回数据格式不正确')
        }

        let generatedText = ''
        for (const message of data.messages) {
            if (message.type === 'answer' && message.content_type === 'text') {
                generatedText = message.content
                break
            }
            if (message.type === 'tool_response' && message.content_type === 'text') {
                try {
                    const toolData = JSON.parse(message.content)
                    if (toolData.output) {
                        generatedText = toolData.output
                        break
                    }
                } catch (e) {
                    console.error('解析tool_response失败:', e)
                }
            }
        }

        if (generatedText) {
            generatedText = generatedText.replace(/^扩写后的图片提示词：/, '').trim()
            contentTheme.value = generatedText
            ElMessage.success('提示词生成成功！')
        } else {
            throw new Error('未获取到有效的提示词')
        }

    } catch (error) {
        console.error('生成提示词失败:', error)
        ElMessage.error(`提示词生成失败: ${error.message}`)
    } finally {
        isGeneratingPrompt.value = false
    }
}

const isValidUrl = (url) => {
    try {
        if (typeof url !== 'string') return false

        if (url.startsWith('https://s.coze.cn/')) return true

        new URL(url)
        return url.match(/^https?:\/\/.+\..+/)
    } catch {
        return false
    }
}

const extractImageUrl = (eventData) => {
    try {
        const data = JSON.parse(eventData)

        if (data.type === "tool_response" && data.content_type === "text") {
            try {
                const contentData = JSON.parse(data.content)
                if (contentData.output && isValidUrl(contentData.output)) {
                    return contentData.output
                }

                if (contentData.x_aiplugin_extra_info) {
                    const extraInfo = JSON.parse(contentData.x_aiplugin_extra_info)
                    if (extraInfo['FLOW:workflow:called_plugin_ids']) {
                        const flowData = JSON.parse(extraInfo['FLOW:workflow:called_plugin_ids'])
                        if (flowData.data && isValidUrl(flowData.data)) {
                            return flowData.data
                        }
                    }
                }
            } catch (e) {
                console.error('解析tool_response内容失败:', e)
            }
        }

        if (data.type === "answer" && data.content_type === "text") {
            const markdownMatch = data.content.match(/!\[.*?\]\((.*?)\)/)
            if (markdownMatch && markdownMatch[1] && isValidUrl(markdownMatch[1])) {
                return markdownMatch[1]
            }

            const urlMatch = data.content.match(/https?:\/\/[^\s]+/)
            if (urlMatch && isValidUrl(urlMatch[0])) {
                return urlMatch[0]
            }
        }

        if (data.type === "verbose" && data.content_type === "text") {
            try {
                const verboseData = JSON.parse(data.content)
                if (verboseData.data) {
                    const dataContent = JSON.parse(verboseData.data)
                    if (dataContent.FinData && isValidUrl(dataContent.FinData)) {
                        return dataContent.FinData
                    }
                }
            } catch (e) {
                console.error('解析verbose内容失败:', e)
            }
        }
    } catch (e) {
        console.error('解析事件数据失败:', e)
    }

    return null
}

const startCreation = async () => {
    if (!contentTheme.value || contentTheme.value.trim() === '') {
        ElMessage.warning('请输入图片主题')
        return
    }
    isGenerating.value = true
    generatedImage.value = null
    try {
        const modifiedContent = `${contentTheme.value}\n\n重要要求：在生成的图片中央以大号醒目文字显示以下关键词："${promptKeywords.value}"，文字要清晰可见，与图片主题协调。`
        const response = await fetch('https://api.coze.cn/v3/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer pat_AhtNhxy0TRJmNkCAHepyMbBOC85FowE9sJEHYSEo8JLJtRles75yi8aJQmscVvZK',
            },
            body: JSON.stringify({
                bot_id: '7530914205952819200',
                user_id: '123456',
                additional_messages: [
                    {
                        role: 'user',
                        type: 'question',
                        content_type: 'text',
                        content: modifiedContent,
                    },
                ],
                stream: true,
            }),
        })
        if (!response.ok) {
            const errorData = await response.json()
            throw new Error(errorData.msg || '图片生成请求失败')
        }
        if (!response.body) {
            throw new Error('无法获取响应流')
        }
        const reader = response.body.getReader()
        const decoder = new TextDecoder('utf-8')
        let buffer = ''
        while (true) {
            const { done, value } = await reader.read()
            if (done) break
            const chunk = decoder.decode(value, { stream: true })
            buffer += chunk
            const lines = buffer.split(/\r\n|\r|\n/)
            buffer = lines.pop() || ''
            for (const line of lines) {
                if (line.startsWith('data:')) {
                    const eventData = line.substring(5).trim()
                    if (eventData === '[DONE]') break
                    const imageUrl = extractImageUrl(eventData)
                    if (imageUrl) {
                        generatedImage.value = imageUrl
                        ElMessage.success('图片生成成功！')
                        break
                    }
                }
            }
            if (generatedImage.value) break
        }
        if (!generatedImage.value) {
            throw new Error('未获取到有效图片URL')
        }
    } catch (error) {
        console.error('生成失败:', error)
        ElMessage.error(`生成失败: ${error.message}`)
    } finally {
        isGenerating.value = false
    }
}

const clearContent = () => {
    contentTheme.value = ''
    promptKeywords.value = ''
    selectedStyle.value = ''
}

const clearGeneratedImage = () => {
    generatedImage.value = null
}

const exportImage = async () => {
    if (!generatedImage.value) return
    try {
        if (!isElectron) {
            const link = document.createElement('a')
            link.href = generatedImage.value
            link.download = `生成的图片-${new Date().getTime()}.jpg`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            ElMessage.success('已开始下载图片')
            return
        }
        const result = await ipcRenderer.invoke('show-save-dialog', {
            title: '保存图片',
            defaultPath: path.join(
                require('os').homedir(),
                'Downloads',
                `生成的图片-${new Date().getTime()}.jpg`
            ),
            filters: [
                { name: '图片文件', extensions: ['jpg', 'jpeg', 'png'] }
            ]
        })
        if (!result.canceled && result.filePath) {
            const response = await fetch(generatedImage.value)
            const blob = await response.blob()
            const arrayBuffer = await blob.arrayBuffer()
            const buffer = Buffer.from(arrayBuffer)
            fs.writeFile(result.filePath, buffer, (err) => {
                if (err) {
                    console.error('保存失败:', err)
                    ElMessage.error('图片保存失败')
                } else {
                    ElMessage.success(`图片已保存到: ${result.filePath}`)
                    ipcRenderer.send('show-item-in-folder', result.filePath)
                }
            })
        }
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error(`导出失败: ${error.message}`)
    }
}
</script>

<style scoped>
.generation-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    box-sizing: border-box;
}

.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 16px 0;
}

.tabs {
    padding-bottom: 8px;
}

.content-wrapper {
    display: flex;
    height: calc(100% - 80px);
    overflow: hidden;
}

.input-panel {
    flex: 0 0 380px;
    padding: 24px 20px;
    display: flex;
    flex-direction: column;
}

.form-container {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.style-select,
.keywords-input {
    width: 100%;
    margin-bottom: 16px;
}

.prompt-generator {
    width: 100%;
    display: flex;
    gap: 8px;
}

.prompt-generator .keywords-input {
    flex: 1;
}

.generate-btn {
    width: 100%;
    flex-shrink: 0;
}

.theme-input,
.model-select,
.ratio-select {
    width: 100%;
}

:deep(.tall-textarea .el-textarea__inner) {
    height: 186px !important;
    min-height: 186px !important;
    padding-top: 12px;
    line-height: 1.5;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-y: auto;
    resize: none;
}

.action-buttons {
    display: flex;
    margin-top: auto;
    padding-top: 20px;
    border-top: 1px solid #f1f5f9;
    gap: 12px;
}

.action-buttons .el-button {
    flex: 1;
}

.divider {
    width: 1px;
    background: #e2e8f0;
    margin: 10px 0;
}

.output-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 24px;
}

.output-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
}

.output-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #f8fafc;
    box-sizing: border-box;
    border-radius: 8px;
    padding: 20px;
    width: 100%;
    min-height: 80%;
}

.image-preview {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: zoom-in;
    transition: all 0.3s;
    max-width: 100%;
    max-height: 100%;
    overflow: hidden;
    position: relative;
}

@media (max-width: 768px) {
    .content-wrapper {
        flex-direction: column;
    }

    .input-panel {
        flex: 1;
        width: 100%;
    }

    .output-content {
        max-width: 100%;
        max-height: 400px;
    }
}

.image-preview:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>